package com.vvlhw.pptmall.product.service.impl;

import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vvlhw.common.utils.PageUtils;
import com.vvlhw.common.utils.Query;

import com.vvlhw.pptmall.product.dao.CategoryDao;
import com.vvlhw.pptmall.product.entity.CategoryEntity;
import com.vvlhw.pptmall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void updateAddGood(Long catId) {
        CategoryEntity categoryEntity = this.baseMapper.selectById(catId);
        categoryEntity.setProductCount(categoryEntity.getProductCount() + 1);
        this.updateById(categoryEntity);
    }

    @Override
    public void updateDeleteGood(Long[] catIds) {
        // 删的商品可能有同类，也就是我需要得到 A分类 有多少、B分类有多少
        // 然后更新表 减去刚刚统计的信息
        Map<Long, Long> map = Arrays.stream(catIds).collect(Collectors.groupingBy(Long::valueOf, Collectors.counting()));
//        map.forEach((k, v) -> System.out.println(k + ":" + v));
//        System.out.println(map.keySet());
        List<CategoryEntity> list = this.baseMapper.selectBatchIds(map.keySet());
        list.forEach(categoryEntity -> categoryEntity.setProductCount(categoryEntity.getProductCount().intValue() - map.get(categoryEntity.getCatId()).intValue()));

        this.updateBatchById(list);
    }

}